package com.xiaomei.manager.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xiaomei.manager.dao.SysOrganizationMapper;
import com.xiaomei.manager.model.SysOrganization;
import com.xiaomei.manager.service.IOrganizationService;

@Service
public class OrganizationServiceImpl implements IOrganizationService{
	
	@Autowired
	private SysOrganizationMapper sysOrganMapper;
	
	/**
	 * 创建组织机构
	 */
    public SysOrganization createOrganization(SysOrganization organization){
    	if(sysOrganMapper.insert(organization) > 0){
    		organization.setId(sysOrganMapper.selectLastInsertID());
    		
    		return organization;
    	}else{
    		return null;
    	}
    }
    
   /**
    * 更新组织机构
    */
    public SysOrganization updateOrganization(SysOrganization organization){
    	if(sysOrganMapper.updateByPrimaryKey(organization) > 0){
    		return organization;
    	}else{
    		return null;
    	}
    	
    }
    
    /**
     * 根据编号删除组织机构信息，以及子级组织机构
     */
    public void deleteOrganization(Long organizationId){
    	SysOrganization organization = sysOrganMapper.selectByPrimaryKey(organizationId);
    	if(sysOrganMapper.deleteByPrimaryKey(organizationId) > 0){
    		sysOrganMapper.deleteByParentids(makeSelfAsParentIds(organization)+"%");
    	}        
    }

    /**
     * 根据编号查询组织机构
     */
    public SysOrganization findOne(Long organizationId){
    	return sysOrganMapper.selectByPrimaryKey(organizationId);
    }
    
    /**
     * 查询所有的组织机构信息
     */
    public List<SysOrganization> findAll(){
    	return sysOrganMapper.selectAll();
    }

    public List<SysOrganization> findAllWithExclude(SysOrganization excludeOraganization){
    	Map map = new HashMap();
    	map.put("id", excludeOraganization.getId());
    	map.put("parentIds", makeSelfAsParentIds(excludeOraganization) + "%");
    	return sysOrganMapper.selectAllWithExclude(map);
    }

    public void move(SysOrganization source, SysOrganization target){
    	Map map1 = new HashMap();
    	map1.put("parentId", target.getId());
    	map1.put("parentIds", target.getParentIds());
    	map1.put("Id", source.getId());
    	sysOrganMapper.updateByPrimaryKeyap(map1);
    	Map map2 = new HashMap();
    	map2.put("parentIds1", makeSelfAsParentIds(target));
    	map2.put("parentIds2", makeSelfAsParentIds(source));
    	map2.put("parentIds3", makeSelfAsParentIds(source)+"%");
    	sysOrganMapper.updateByPrimaryKeysp(map2); 
    }
    
    public String makeSelfAsParentIds(SysOrganization sys) {
        return sys.getParentIds() + sys.getId() + "/";
    }
}
